Page({
  data: {
    currentTime: '0:00',  
    duration: '2:00',     
    progressPercent: 0,   
    audioContext: null,   
    isPlaying: false,     
    audioTitle: '',     
    title:'',
  },

  onLoad: function (options) {
    const fileURL = options.fileURL;
    const title = options.title;
    this.setData({
      title:title,

    })
    console.log('id:',fileURL)
    this.audioContext = wx.createInnerAudioContext();
    
    this.getCachedAudio(fileURL);
  },

  
  getCachedAudio: function (fileURL) {
    wx.cloud.getTempFileURL({
      fileList: [fileURL], 
      success: (res) => {
        console.log('获取到的 fileList:', res.fileList);
  
        const audioUrl = res.fileList[0].tempFileURL; 

        let doubleEncodedUrl = audioUrl.replace(/%/g, '%25');
        console.log('音频文件的临时 URL:', doubleEncodedUrl);
        
        this.audioContext.src = doubleEncodedUrl;
        this.audioContext.onCanplay(() => {
          console.log('音频元数据加载完成 (onCanplay)');
          setTimeout(() => {
            const duration = this.audioContext.duration;
            console.log('音频时长：', duration);
            if (duration > 0) {
              const formattedDuration = this.formatTime(duration);
              this.setData({ duration: formattedDuration });
            } else {
              console.log('音频时长为 0，可能是加载过程中出现了问题');
            }
          }, 1000);  
        });
  
        this.audioContext.onTimeUpdate(() => {
          const currentTime = this.audioContext.currentTime;
          const duration = this.audioContext.duration;
          const progressPercent = (currentTime / duration) * 100;
  
          this.setData({
            currentTime: this.formatTime(currentTime),
            progressPercent: progressPercent,
          });
        });
  
        this.audioContext.onEnded(() => {
          this.setData({ isPlaying: false });
        });
      },
      fail: (err) => {
        console.error('获取临时文件 URL 失败:', err);
      },
    });
  },
  
  

  // 播放或暂停音频
  playAudio: function () {
    if (this.data.isPlaying) {
      // 暂停音频
      this.audioContext.pause();
    } else {
      // 播放音频
      this.audioContext.play();
    }

    // 切换播放状态
    this.setData({ isPlaying: !this.data.isPlaying });
  },

  // 点击刷新图标，音频回到原点并重新播放
  resetAudio: function () {
    if (this.audioContext) {
      // 将音频进度重置为0
      this.audioContext.seek(0);
    }
  },

  // 格式化时间为 mm:ss 格式
  formatTime: function (time) {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  },

  onUnload: function () {
    // 释放音频上下文
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  },

  tips: function () {
    wx.showToast({
      title: '没有更多了',
    });
  }
});
